<script setup>
import { useDiscussListQuery } from '@/composables/useTopicDataQuery'
import { useRoute } from 'vue-router'
import SettingTitle from './components/SettingTitle.vue'
import LfButton from '@/components/commonUI/LfButton.vue'
import LfDialog from '@/components/commonUI/LfDialog.vue'
import { fetchDiscussAdd, fetchDiscussDel } from '@/axios/api/topic'
const route = useRoute()

const { data, isLoading, isFetching, fetchNextPage, hasNextPage, refetch } = useDiscussListQuery(route.params.topicId)

const showDialog = ref(false)

const title = ref('')
const introduce = ref('')

const handleOk = async () => {
  const res = await fetchDiscussAdd({
    title: title.value,
    introduce: introduce.value,
    topicId: route.params.topicId,
  })

  if (res.code === 0) {
    showDialog.value = false
    title.value = ''
    introduce.value = ''
    refetch()
  }
}

const createTopicDialogRef = ref(null)

const handleCreateTopic = () => {
  showDialog.value = true
}

const handleDeleteTopic = async (id) => {
  const res = await fetchDiscussDel({
    id,
  })

  if (res.code === 0) {
    refetch()
  }
}
</script>

<template>
  <div>
    <LfDialog
      ref="createTopicDialogRef"
      :isShow="showDialog"
      width="500px"
      height="400px"
      title="创建话题"
      @ok="handleOk"
      @close="showDialog = false"
      @cancel="showDialog = false">
      <div class="flex-1 flex flex-col gap-4 pt-[40px]">
        <div class="border-1 border-[--line-1] rounded-md p-2">
          <div class="text-sm">名称</div>
          <div>
            <input placeholder="请输入话题名称" type="text" v-model="title" />
          </div>
        </div>
        <div class="border-1 border-[--line-1] rounded-md p-2">
          <div class="text-sm">描述</div>
          <div>
            <textarea placeholder="请输入话题描述" type="text" class="w-full h-full" v-model="introduce" />
          </div>
        </div>
      </div>
    </LfDialog>

    <div class="flex justify-between items-center">
      <SettingTitle title="话题列表" />
      <LfButton type="primary" @click="handleCreateTopic">创建话题</LfButton>
    </div>

    <div class="flex flex-col gap-4">
      <template v-for="(page, index) in data?.pages" :key="index">
        <div
          v-for="item in page.result.data"
          :key="item.id"
          class="border-1 border-[--line-1] rounded-md p-2 flex justify-between items-center">
          <div class="">
            <div>
              <div class="text-lg font-bold"># {{ item.title }}</div>
              <div>描述：{{ item.introduce }}</div>
            </div>

            <div class="flex text-sm text-gray-500 gap-3">
              <div>{{ item.readCount }}次浏览</div>
            </div>
          </div>

          <div>
            <LfButton type="danger" @click="handleDeleteTopic(item.id)">删除</LfButton>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>
